import { createRouter, createWebHistory, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw } from 'vue-router'
import useRouterStore from '@/store/modules/router'
import useTabsStore from '@/store/modules/tabs'
import NProgress from '@/utils/nprogress'
import useMenuStore from '@/store/modules/menu'

const files = import.meta.glob('./modules/*.ts', { eager: true })

interface Module {
    default: RouteRecordRaw;
}


export const routes: RouteRecordRaw[] = []
Object.keys(files).forEach(async (path) => {
    routes.push((files[path] as Module).default)
});








const router = createRouter({
    history: import.meta.env.VITE_ROUTER_HISTORY === 'hash' ? createWebHashHistory() : createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: '/layout'
        }, {
            path: '/layout',
            name: 'layout',
            redirect: '/home',
            component: () => import('@/components/Layout/index.vue'),
            children: [
                {
                    path: '/home',
                    name: '首页',
                    meta: {
                        sort: 1,
                        icon: 'icon-home'
                    },
                    component: () => import('@/views/Home/index.vue')
                }
            ]
        },
        ...routes,

        { path: '/:pathMatch(.*)*', name: '404', component: () => import('@/components/NotFound/index.vue') },


    ]
})


router.beforeEach((to, from, next) => {
    NProgress.start();
    const routerStore = useRouterStore()
    const tabsStore = useTabsStore()
    const menuStore = useMenuStore()

    // 判断tab是否为空
    if (Array.isArray(tabsStore.tabList) && !tabsStore.tabList.length) {
        tabsStore.updateTabsList({ name: '首页', path: '/home' })
    }

    // 不等于404的前提下 tab不存在
    if (to.name !== '404' && tabsStore.tabList.filter(item => item.path === to.path).length === 0) {
        tabsStore.updateTabsList({ name: to.name as string, path: to.path })
    }

    routerStore.changeRoutePath(to)
    // 计算菜单总数
    console.log(routes, 'routes');

    menuStore.calcMenuTotal(routes)
    next()
})


router.afterEach(() => {
    NProgress.done();
});


export default router